package in.muton.edushare.wicket.models;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.model.IModel;

public class CayenneList<T> implements IModel<List<IModel<T>>> {

	public CayenneList(List<T> rawObjList) {
		objList = new ArrayList<IModel<T>>();
		if (rawObjList == null)
			return;
		for (T r : rawObjList) {
			objList.add(new CayenneModel<T>(r));
		}
	}
	
	public CayenneList<T> add(IModel<T> obj){
		add(obj.getObject());
		return this;
	}

	public CayenneList<T> add(T obj) {
		objList.add(new CayenneModel<T>(obj));
		return this;
	}
	
	public CayenneList<T> add(CayenneList<T> list){
		List<IModel<T>> l = list.getObject(); 
		for(IModel<T> t:l){
			add(t.getObject());
		}
		return this;
	}
	
	public CayenneList<T> add(List<T> list){
		for(T t:list){
			add(t);
		}
		return this;
	}

	public void remove(T obj) {
		Iterator<IModel<T>> it = objList.iterator();
		while (it.hasNext()) {
			if (obj == it.next().getObject()) {
				it.remove();
			}
		}
	}

	public void remove(IModel<T> model) {
		remove(model.getObject());
	}
	
	public void clear(){
		objList = new ArrayList<IModel<T>>();
	}

	public boolean contains(T obj) {
		for (IModel<T> m : objList) {
			if (m.getObject() == obj)
				return true;
		}
		return false;
	}

	public boolean contains(IModel<T> model) {
		return contains(model.getObject());
	}

	public List<IModel<T>> getObject() {
		return objList;
	}

	public void setObject(List<IModel<T>> arg0) {
		this.objList = arg0;
	}
	
	public List<T> getUtilList(){
		List<T> newList = new ArrayList<T>();
		for(IModel<T> m:objList){
			newList.add(m.getObject());
		}
		return newList;
	}

	public void detach() {
	}

	private List<IModel<T>> objList = null;
	private static final long serialVersionUID = -58770022223145148L;
}
